/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.pig4cloud.pig.mt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.mt.common.api.utils.Query;
import com.pig4cloud.pig.mt.entity.WxMsgTemplate;
import com.pig4cloud.pig.mt.mapper.WxMsgTemplateMapper;
import com.pig4cloud.pig.mt.service.WxMsgTemplateService;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 消息模板
 *
 * @author JLM
 * @date 2021-03-05 11:45:09
 */
@Service
public class WxMsgTemplateServiceImpl extends ServiceImpl<WxMsgTemplateMapper, WxMsgTemplate> implements WxMsgTemplateService {
	@Autowired
	private WxMpService wxService;

	@Override
	public IPage queryPage(Map<String, Object> params) {
		String title = (String) params.get("title");
		String name = (String) params.get("name");
		String appid = (String) params.get("appid");
		IPage<WxMsgTemplate> page = this.page(
				new Query<WxMsgTemplate>().getPage(params),
				new QueryWrapper<WxMsgTemplate>()
						.eq(!StringUtils.isEmpty(appid), "appid", appid)
						.like(!StringUtils.isEmpty(title), "title", title)
						.like(!StringUtils.isEmpty(name), "name", name)
		);

		return page;
	}

	@Override
	public WxMsgTemplate selectByName(String name) {
//        Assert.hasText(name, "模板名称不得为空");
		return this.getOne(new QueryWrapper<WxMsgTemplate>()
				.eq("name", name)
				.eq("status", 1)
				.last("LIMIT 1"));
	}

	@Override
	public void syncWxTemplate(String appid) throws WxErrorException {
		List<WxMpTemplate> wxMpTemplateList= wxService.getTemplateMsgService().getAllPrivateTemplate();
		List<WxMsgTemplate> templates = wxMpTemplateList.stream().map(item->new WxMsgTemplate(item,appid)).collect(Collectors.toList());
		this.saveBatch(templates);
	}
}
